<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2024/4/10
 * Time: 12:01
 */

namespace plugin\admin\app\logic\order;


use plugin\admin\app\logic\BaseLogic;
use plugin\admin\app\model\font\FontModel;
use plugin\admin\app\model\user\UserModel;
use plugin\admin\app\model\user\UserRechargeOrderModel;
use support\Db;
use support\Request;
use support\Response;

class OrderLogic extends BaseLogic
{
    protected static $instance;

    public function __construct()
    {
        $this->model = new UserRechargeOrderModel();
    }

    public static function getInstance()
    {
        //        if(is_object(self::$instance)){
//            return self::$instance;
//        }

        return new self();
    }

    // 更新【充值日期 = 注册日期】的用户订单
    public function newUserRecharge()
    {
        $id_arr = [];
        // 把所有【充值日期 = 注册日期】的user_sn找出来
        $new_recharge_order_id_arr = Db::table('view_new_user_recharge_order_id')->get();
        if($new_recharge_order_id_arr && count($new_recharge_order_id_arr) > 0){
            foreach($new_recharge_order_id_arr as $nroiav){
                $id_arr[] = $nroiav->id;
            }
        }

        if(count($id_arr) > 0){
            (new UserRechargeOrderModel())->whereIn('id',$id_arr)->update(['is_new_user_recharge' => 1]);
        }
    }

    // 更新巨量推广的用户订单
    public function oceanenginePromotionUser()
    {
        $id_arr = [];
        $res = Db::table('view_recharge_order_oceanengine_promotion_user')->get();
        if($res && count($res) > 0){
            foreach($res as $v){
                $id_arr[] = $v->id;
            }
        }

        if(count($id_arr) > 0){
            (new UserRechargeOrderModel())->whereIn('id',$id_arr)->update(['is_oceanengine_promotion_user' => 1]);
        }
    }

    public function select(Request $request): Response
    {
        $this->newUserRecharge(); // 优化点：订单量上来了再把它抽到定时任务里
        $this->oceanenginePromotionUser(); // 优化点：订单量上来了再把它抽到定时任务里
        $field = $request->input('field');
        if($field==false){
            $request->inputSet('field','created_at');
            $request->inputSet('order','desc');
        }

        return parent::select($request);
    }

    protected function formatNormal($items, $total): Response
    {
        $userMap = $this->getListMapById(UserModel::getInstance(),$items,'user_sn','user_sn',['field'=>['nickname']]);

        foreach($items as &$val){
            $val['nickname'] = isset($userMap[$val['user_sn']])?$userMap[$val['user_sn']]['nickname']:'';
            $val['expires_date'] = !empty($val['expires_date']) ? date('Y-m-d H:i:s',$val['expires_date']):'';
        }

        $totalData = $this->getOrderTotal();
        return json(['code' => 0, 'msg' => 'ok', 'count' => $total, 'data' => $items,'total_data'=>$totalData]);
    }

    public function getOrderTotal()
    {
        $data = [];
        [$where, $format, $limit, $field, $order] = $this->selectInput(request());
        if(!empty($where['pay_time'])){
            $where[] = ['pay_time','between',$where['pay_time']];
            unset($where['pay_time']);
        }
        if(!empty($where['created_at'])){
            $where[] = ['created_at','between',$where['created_at']];
            unset($where['created_at']);
        }

        //累计订单金额/数
        $where1 = $where;
        $where1['order_status'] = 6;
        $data['total_order_amount'] = $this->model->getWhere($where1)->sum('money');
        $data['total_order_nums'] = $this->model->getWhere($where1)->count();

        //开通会员订单金额/数
        $where2 = $where;
        $where2['order_status'] = 6;
        $where2['product_type'] = 1;
        $data['total_vip_order_amount'] = $this->model->getWhere($where2)->sum('money');
        $data['total_vip_order_nums'] = $this->model->getWhere($where2)->count();

        //购买点数订单金额/数
        $where2 = $where;
        $where2['order_status'] = 6;
        $where2['product_type'] = 2;
        $data['total_buy_order_amount'] = $this->model->getWhere($where2)->sum('money');
        $data['total_buy_order_nums'] = $this->model->getWhere($where2)->count();

        //累计订单人数
        $where3 = $where;
        $where3['order_status'] = 6;
        $subQuery = (new UserRechargeOrderModel())->getWhere($where3)->groupBy('user_sn')->select([Db::raw('count(1) counts')]);
        $data['total_order_user_peoples'] = (new UserRechargeOrderModel())->setTable(Db::raw("({$subQuery->toSql()}) a"))->mergeBindings($subQuery->getQuery())->count();

        //新用户充值比例
        $where4 = $where;
        if(isset($where4['is_new_user_recharge']) && $where4['is_new_user_recharge'] == 0){
            $data['new_user_recharge_ratio'] = 0;
        }else{
            if(!isset($where4['is_new_user_recharge'])){
                $where4['is_new_user_recharge'] = 1;
            }
            $n_order = $this->model->getWhere($where4)->count();
            if($n_order == 0){
                $data['new_user_recharge_ratio'] = 0;
            }
            $data['new_user_recharge_ratio'] = round(($n_order / $data['total_order_nums'] * 100), 2);
            if($data['new_user_recharge_ratio'] > 100){
                $data['new_user_recharge_ratio'] = 100;
            }
        }

        //老用户充值比例
        $data['old_user_recharge_ratio'] = 100 - $data['new_user_recharge_ratio'];

        $data['new_user_recharge_ratio'] .= '%';
        $data['old_user_recharge_ratio'] .= '%';

        return $data;
    }
}